<?php
class Third_Panel {

	private $entity_name;
	private $view;
	private $data;
	private $form;
	private $values;
	private $editing = false;
	private $toSmarty = false;
	private $validation = true;
	private $token = true;
	private $third = null;

	public function  __construct($entity, $data = null){
		$this->entity 	= $entity;
		$this->data 	= $data;
		$this->view = Zend_Registry::get('view');
	}

	function setValues( $values ) {
		$this->values = $values;
	}

	function setEditing( $editing = true ){
		$this->editing = $editing;
	}
	
	function getEntity(){
		return $this->entity;
	}

	function getValues( ) {
		return $this->values;
	}

	public function removeToken(){
		$this->token = false;
	}

	public function getForm(){

		$this->getFormProfile();

		//POPULA FORMULARIO COM DADOS POSTADOS
		$values = $this->getValues();

		if( $values )
			$this->form->populate( $this->getValues() );

		if( $this->validation )
			$this->addFormJsValidation();

		return $this->form;
	}
	
	public function addFormJsValidation(){

		$formId = $this->form->getAttrib('id');

		if( $formId ){
			$validation = new Third_Form_ExtraTag( 'validation' );
			$validation->setValue( "<div id=\"".$formId."Action\"></div>" );

			$validation->removeDecorator('DtDdWrapper')
						->removeDecorator('label')
   						->removeDecorator('HtmlTag');

			$this->form->addElement( $validation );
			
			$this->view->jQuery()->onLoadCaptureStart();
			echo "
				$(\"#".$formId."\").validate({ meta: \"validate\" });
			";
			$this->view->jQuery()->onLoadCaptureEnd();
		}
	}

	public function removeFormJsValidation(){
		$this->validation = false;
	}

	public function getFormValidationsErrors( ){

		$erros = $this->form->getMessages();
/*
		$errorText = "<div><ul>";

		if( isset( $this->entity ))
			$campos = $this->entity->getFields();

			foreach($erros as $field=>$msgs){
				foreach($msgs as $key=>$msg){

					if( isset( $campos[$field] ) )
						$campo = $campos[$field]["label"];
					else
						$campo = $field;
					
					$errorText .= "<li> <b>". $campo ."</b> ".$msg."</li>";
				}
			}

		$errorText .= "</div>";
				*/
		return $erros;
	}

	public function getFormProfile(){

		$this->form = new Zend_Form();
		$this->form->setView( new Zend_View() );

		// $randomValue = $this->third->randomValue();

		if( isset( $this->entity ) && !$this->form->getAttrib('id') )
			$this->form->setAttrib( 'id', $this->entity->configs["reference"].'Form' );

			//$translate = Zend_Registry::get('translate');
			// $this->form->setTranslator($translate);

			//ADICIONA ELEMENTOS AO FORM
			$this->addElements();

			if( $this->token ){
				
				// Zend_Debug::dump( $this->token );
				
				/* PREVINE CROSS_SITE */
				/*
				$no_csrf = new Zend_Form_Element_Hash('formToken', array('salt' => $this->form->getAttrib('id') ) );
				$no_csrf->setAutoInsertNotEmptyValidator(false);
				$no_csrf->removeDecorator('DtDdWrapper')
						->removeDecorator('label')
	   					->removeDecorator('HtmlTag');

				$this->form->addElement( $no_csrf );
				*/
			}

		return $this->form;	
	}
	
	public function addElements(){
		$fields = "";

		if( isset($this->entity->fields) )
			$fields = $this->entity->fields;

		if(is_array($fields)){
			$campos_nomes = array_keys( $fields );

			foreach($campos_nomes as $campo)
				$campos[$campo] = $this->entity->getFieldOptions( $campo );

		//CAMPOS A SEREM EXIBIDOS
		/* if( $this->fieldsShow ){
			//ADICIONA CHAVES ESTRANGEIRAS QUE NAO PODEM SER NULAS
			if( $entity->fields_fk )
			$this->fieldsShow  = array_merge( $entity->fields_fk, $this->fieldsShow );

			// SEPARA SO OS CAMPOS EXIBIDOS
			$campos = array_intersect_key($campos, array_flip( $this->fieldsShow ) );
			}	 */

			// MONTA OBJETOS
			foreach( $campos as $field_name=>$field_options ){

				$field_options = Third_Funcs::array_map_tree('utf8_decode', $field_options );
				
				$component = $field_options['component'];

				switch( $component ){
					case 'hidden':
						$campo = new Third_Form_Hidden( $field_name , $field_options );
						break;
					case 'input':
						$campo = new Third_Form_Input( $field_name , $field_options );
						break;
					case 'password':
						$campo = new Third_Form_Password( $field_name , $field_options );
						break;
					case 'reset':
						$campo = new Third_Form_Reset( $field_name , $field_options );
						break;
					case 'submit':
						$campo = new Third_Form_Submit( $field_name , $field_options );
						break;
					case 'button':
						$campo = new Third_Form_Button( $field_name , $field_options );
						break;
					case 'select':
						$campo = new Third_Form_Select( $field_name , $field_options );
						break;
					case 'textarea':
						$campo = new Third_Form_Textarea( $field_name , $field_options );
						break;
					case 'upload':
						$campo = new Third_Form_Upload( $field_name , $field_options );
						break;
					case 'radio':
						$campo = new Third_Form_Radio( $field_name , $field_options );
						break;
					case 'checkbox':
						$campo = new Third_Form_Checkbox( $field_name , $field_options );
						break;
					case 'captcha':
						$campo = new Third_Form_Captcha( $field_name , $field_options );
						break;
					case 'hash':
						$campo = new Third_Form_Hash( $field_name , $field_options );
						break;
					case 'image':
						$campo = new Third_Form_Image( $field_name , $field_options );
						break;
					case 'multicheckbox':
						$campo = new Third_Form_MultiCheckbox( $field_name , $field_options );
						break;
					case 'multiselect':
						$campo = new Third_Form_Multiselect( $field_name , $field_options );
						break;
					default:
						$campo = null;
						break;
				}

				if($campo){
					$element = $campo->get( $this->editing );
					if( $element ){

						$element->addDecorators(array(
						  //  array('ViewHelper'), BUG IN Zend_Form_Element_File
						    array('Errors'),
						    array('Description', array('tag' => 'p', 'class' => 'description')),
						    array('HtmlTag', array('tag' => 'div', 'class' => 'field') ),
						    array('Label', array('class'=>'label')),
					    	array(
								array('row' => 'HtmlTag'), 
					    		array('tag' => 'div', 'id'=>$component."_".$field_name, 'class'=>"field_container $component")
							)
						));

						switch( $component){
							case 'hidden':
								$element->removeDecorator('DtDdWrapper')
										->removeDecorator('label')
	              						->removeDecorator('HtmlTag');
							break;
							case 'submit':
								$element->removeDecorator('DtDdWrapper')
										->removeDecorator('label');
							break;
						}
	
						$this->form->addElement( $element );
					}
				}
			}
		}
	}
}
?>